package com.tensquare.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tensquare.entity.Article;
import com.tensquare.service.IArticleService;

/**
 * <p>
 * 文章 前端控制器
 * </p>
 *
 * @author caoxingsheng
 * @since 2019-06-01
 */
@RestController
@RequestMapping("/article")
public class ArticleController extends BaseController {

	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private IArticleService articleService;

	/**
	 * 根据ID查询实体
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/getById/{id}")
	public Article getById(@PathVariable String id) {
		// 从缓存中提取
		Article article = (Article) redisTemplate.opsForValue().get("article_" + id);
		// 如果缓存没有则到数据库查询并放入缓存
		if (article == null) {
			article = articleService.getById(id);
			redisTemplate.opsForValue().set("article_" + id, article);
		}
		return article;
	}

	/**
	 * 修改
	 * 
	 * @param article
	 */
	@PutMapping("/update")
	public void update(@RequestBody Article article) {
		redisTemplate.delete("article_" + article.getId());// 删除缓存
		articleService.updateById(article);
	}

	/**
	 * 删除
	 * 
	 * @param id
	 */
	@DeleteMapping("/deleteById/{id}")
	public void deleteById(@PathVariable String id) {
		redisTemplate.delete("article_" + id);// 删除缓存
		articleService.removeById(id);
	}

}
